﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace CccNh
{
    public static class TypeExtensions
    {
        public static bool Inherits(this Type toCheck, Type generic)
        {
            while (toCheck != typeof(object))
            {
                var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
                if (generic == cur)
                {
                    return true;
                }
                toCheck = toCheck.BaseType;
            }
            return false;
        }
        public static bool Implements(this Type toCheck, Type generic)
        {
            return toCheck.GetInterfaces()
                .Select(@interface => @interface.IsGenericType ? @interface.GetGenericTypeDefinition() : @interface)
                .Any(cur => generic == cur);
        }

        public static bool CanBeInstantiated(this Type type)
        {
            return type.IsClass && !type.ContainsGenericParameters && !type.IsAbstract;
        }
        public static IEnumerable<Type> GetTypesSafe(this Assembly assembly)
        {
            return assembly.GetTypes().Where(t => !string.IsNullOrEmpty(t.Namespace));
        }

    }
}